﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class GameEnterStateLoadZip : GameEnterState
{
    public GameEnterStateLoadZip(IGameEnterControl inControl)
        : base(inControl, GameState.UNZIP)
    {

    }

    private void OnLoading(UnityWebRequest uwq)
    {
        Debug.Log(uwq.downloadProgress);
    }

    private void OnLoadFinish(byte[] datas)
    {
        string destPath = PathDefine.PersistentDataPath + PathDefine.FileList;
        if(File.Exists(destPath)) { File.Delete(destPath); }
        FileStream file = File.Create(destPath);
        file.Write(datas, 0, datas.Length);
        file.Close();
        control.PlayNext();
    }

    public override void Start()
    {
        // using www
        // Load file from streamingAssetsPath to persistentAssetPath
        EngineFramework.Instance.StartCoroutine(LoadFileWWW(PathDefine.StreamingAssetsPath + PathDefine.FileList, OnLoadFinish, OnLoading));
    }

    private IEnumerator LoadFileWWW(string path, Action<byte[]> OnLoadCallback, Action<UnityWebRequest> OnLoading = null)
    {
        using (UnityWebRequest uwq = UnityWebRequest.Get(path)) {
            yield return uwq.SendWebRequest();
            OnLoading?.Invoke(uwq);
            if (!string.IsNullOrEmpty(uwq.error)) {
                Debug.LogErrorFormat("{0} => {1}", uwq.error, path);
            }
            OnLoadCallback?.Invoke(uwq.downloadHandler.data);
            uwq.Dispose();
        }
        yield return null;
    }

}
